package com.small.site.security;

import com.small.site.cache.CacheService;
import com.small.site.config.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author xiaochi
 * @date 2021/12/11 17:32
 * @desc SecurityConfig配置
 */
@Slf4j
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${security.loginUrl}")
    private String loginUrl;
    @Value("${security.logoutUrl}")
    private String logoutUrl;
    @Value("${security.openUrl}")
    private String[] openUrl;
    @Autowired
    private JwtConfig jwtConfig;

    private String[] pubPath(){
        String[] urls = {
                "/**/*.css","/**/*.js","/favicon.ico",
                "/druid/**","/webjars/**","/v2/api-docs","/swagger/**","/swagger-resources/**","/swagger-ui.html"
        };
        String[] path = new String[openUrl.length + urls.length];
        System.arraycopy(openUrl,0,path,0,openUrl.length);
        System.arraycopy(urls,0,path,openUrl.length,urls.length);
        return path;
    }

    @Bean
    public CacheService cacheService(){
        return new CacheService();
    }

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public LoginUserDetailsService loginUserDetailsService(){
        return new LoginUserDetailsService();
    }

    /**
     * 配置认证用户 Provider 与 userDetailsService
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(new JwtAuthenticationProvider(loginUserDetailsService(),bCryptPasswordEncoder()))
            .userDetailsService(loginUserDetailsService()).passwordEncoder(bCryptPasswordEncoder());
    }

    /**
     * 配置拦截请求资源、成功与失败处理器
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        UserLoginFilter userLoginFilter = new UserLoginFilter(loginUrl);
        userLoginFilter.setJwtConfig(jwtConfig);
        userLoginFilter.setAuthenticationManager(authenticationManagerBean());// 必须设置
        JwtTokenAuthenticationFilter jwtTokenAuthenticationFilter = new JwtTokenAuthenticationFilter();
        jwtTokenAuthenticationFilter.setOpenUrl(openUrl);
        jwtTokenAuthenticationFilter.setUserLoginFilter(userLoginFilter);
        jwtTokenAuthenticationFilter.setLoginUserDetailsService(loginUserDetailsService());
        // 注意 filter 顺序，将登录过滤器放在验证过滤器前面，但需要先注册验证过滤器
        http.addFilterBefore(jwtTokenAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
            .addFilterBefore(userLoginFilter,JwtTokenAuthenticationFilter.class)
            .formLogin()
            .loginProcessingUrl(loginUrl)
            .and()
            .logout().logoutUrl(logoutUrl).logoutSuccessHandler(new LogoutHander()).clearAuthentication(true)
            .and()
            .cors()
            .and()
            .csrf().disable()
            .headers().frameOptions().disable().cacheControl().disable() // 开启允许iframe 嵌套。security默认禁用firam跨域与缓存
            .and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS) // 这里使用 token，定制我们自己的 session 策略，调整为让 Spring Security 不创建和使用 session
            .and()
            .authorizeRequests()////验证策略
            .antMatchers(HttpMethod.OPTIONS,"/**").permitAll() // 跨域预检请求
            .antMatchers(pubPath()).permitAll()
            .anyRequest().authenticated(); //所有请求，必须授权才能访问
            // 异常由 JwtTokenAuthenticationFilter 捕获
            //.authenticationEntryPoint((request,response,ex) -> responseJson(response,ResponseCode.TOKEN_ERROR.getCode(),ResponseCode.TOKEN_ERROR.getMessage())) // 匿名用户无权限访问资源时处理器
            //.accessDeniedHandler((request,response,ex) -> responseJson(response,ResponseCode.NOT_PERMISSION.getCode(),ResponseCode.NOT_PERMISSION.getMessage())); // 认证用户无权限访问资源时处理器
    }
}
